package com.hwadee.property.controller.house;

import com.hwadee.property.dto.HousePersonal;
import com.hwadee.property.pojo.House;
import com.hwadee.property.service.IHouseService;
import com.hwadee.property.util.AjaxResult;
import com.hwadee.property.util.DateUtil;
import com.hwadee.property.util.DtoUtil;
import com.hwadee.property.util.JwtUtil;
import com.hwadee.property.dto.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;

/**
 * 房屋信息控制器
 */
@RestController
@RequestMapping("/api/houses")
@Api(tags = "房屋信息-HouseController")
@CrossOrigin
public class HouseController {

    @Autowired
    private IHouseService houseService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private DtoUtil dtoUtil;

    @GetMapping("/personal")
    @ApiOperation(value = "【用户】获取个人房屋信息", notes = "返回个人名下的所有房屋信息列表")
    public AjaxResult getAllHousesPersonal(@RequestHeader("Authorization") String token) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);
            // 进行投诉建议提交
            List<HousePersonal> houses = dtoUtil.listByOwnerIdPersonal(userId);
            return AjaxResult.success(houses);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("token解析异常或其他异常，新增投诉或建议失败");
        }
    }

    /**
     * 【管理员】分页查询房屋信息
     *
     * @param token      授权令牌
     * @param current    当前页码（默认值：1）
     * @param size       每页大小（默认值：10）
     * @param buildingId 楼栋ID（可选）
     * @param communityId 小区ID（可选）
     * @param ownerId    业主ID（可选）
     * @param floor      楼层（可选）
     * @param roomNum    房间数（可选）
     * @param roomNumber 门牌号（可选）
     * @param remark     备注信息（可选）
     * @param startDate  起始时间（可选，格式：yyyy-MM-dd）
     * @param endDate    结束时间（可选，格式：yyyy-MM-dd）
     * @return 分页查询的房屋信息
     */
    @GetMapping("/page")
    @ApiOperation(value = "【管理员】分页查询房屋信息", notes = "支持按楼栋ID和门牌号模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证 Token", required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "int", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页大小", required = true, dataType = "int", paramType = "query", defaultValue = "10"),
            @ApiImplicitParam(name = "buildingId", value = "楼栋ID", required = false, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "communityId", value = "小区ID", required = false, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "ownerId", value = "业主ID", required = false, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "floor", value = "楼层", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "roomNum", value = "房间数", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "roomNumber", value = "门牌号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注信息", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "起始时间", required = false, dataType = "string", paramType = "query", example = "2025-01-01"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", required = false, dataType = "string", paramType = "query", example = "2025-12-31")
    })
    public PageResult<House> getPage(
            @RequestHeader("Authorization") String token,
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "buildingId", required = false) Long buildingId,
            @RequestParam(value = "communityId", required = false) Long communityId,
            @RequestParam(value = "ownerId", required = false) Long ownerId,
            @RequestParam(value = "floor", required = false) Integer floor,
            @RequestParam(value = "roomNum", required = false) Integer roomNum,
            @RequestParam(value = "roomNumber", required = false) String roomNumber,
            @RequestParam(value = "remark", required = false) String remark,
            @RequestParam(value = "startDate", required = false)  String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) throws ParseException {
        return houseService.getPage(current, size, buildingId, communityId, ownerId, floor, roomNum, roomNumber, remark,
                DateUtil.stringToDate(startDate), DateUtil.stringToDate(endDate));
    }

    /**
     * 添加房屋信息
     *
     * @param token      认证Token
     * @param buildingId 所属楼栋ID
     * @param floor      楼层号
     * @param roomNum    房间编号
     * @param roomNumber 门牌号
     * @param remark     备注信息
     * @param ownerId    业主ID（可选）
     * @param checkInDate 入住日期（可选）
     * @return 添加后的房屋信息
     */
    @PostMapping
    @ApiOperation(value = "【管理员】添加房屋信息", notes = "添加新的房屋信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证Token", required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "buildingId", value = "所属楼栋ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "floor", value = "楼层号", required = true, dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "roomNum", value = "房屋数量", required = true, dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "roomNumber", value = "门牌号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注信息", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "ownerId", value = "业主ID", required = false, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "checkInDate", value = "入住日期", required = false, dataType = "string", paramType = "query")
    })
    public AjaxResult addHouse(@RequestHeader("Authorization") String token,
                               @RequestParam Long buildingId,
                               @RequestParam Integer floor,
                               @RequestParam Integer roomNum,
                               @RequestParam String roomNumber,
                               @RequestParam String remark,
                               @RequestParam(required = false) Long ownerId,
                               @RequestParam(required = false) String checkInDate) throws ParseException {
        House house = new House();
        house.setBuildingId(buildingId);
        house.setFloor(floor);
        house.setRoomNum(roomNum);
        house.setRoomNumber(roomNumber);
        house.setRemark(remark);
        if (ownerId != null){
            house.setOwnerId(ownerId);
            if (checkInDate == null) return AjaxResult.fail("需要与户主信息一起同步填写入住日期");
            DateUtil.stringToDate(checkInDate);
            house.setCheckInDate(checkInDate);
        }
        boolean saved = houseService.save(house);
        return saved ? AjaxResult.success(house) : AjaxResult.fail("房屋添加失败");
    }

    /**
     * 更新房屋信息
     *
     * @param token      认证Token
     * @param id         房屋ID
     * @param buildingId 所属楼栋ID（可选）
     * @param floor      楼层号（可选）
     * @param roomNum    房间编号（可选）
     * @param roomNumber 房间门牌号（可选）
     * @param remark     备注信息（可选）
     * @param ownerId    业主ID（可选）
     * @param checkInDate 入住日期（可选）
     * @return 更新后的房屋信息
     */
    @PutMapping("/{id}")
    @ApiOperation(value = "【管理员】更新房屋信息", notes = "根据房屋ID更新房屋信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证Token", required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "id", value = "房屋ID", required = true, dataType = "long", paramType = "path"),
            @ApiImplicitParam(name = "buildingId", value = "所属楼栋ID", required = false, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "floor", value = "楼层号", required = false, dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "roomNum", value = "房屋数量", required = false, dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "roomNumber", value = "房屋门牌号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注信息", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "ownerId", value = "业主ID", required = false, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "checkInDate", value = "入住日期", required = false, dataType = "string", paramType = "query")
    })
    public AjaxResult updateHouse(@RequestHeader("Authorization") String token,
                                  @PathVariable Long id,
                                  @RequestParam(required = false) Long buildingId,
                                  @RequestParam(required = false) Integer floor,
                                  @RequestParam(required = false) Integer roomNum,
                                  @RequestParam(required = false) String roomNumber,
                                  @RequestParam(required = false) String remark,
                                  @RequestParam(required = false) Long ownerId,
                                  @RequestParam(required = false) String checkInDate) throws ParseException {
        House house = new House();
        house.setId(id);
        if (buildingId != null) house.setBuildingId(buildingId);
        if (floor != null) house.setFloor(floor);
        if (roomNum != null) house.setRoomNum(roomNum);
        if (roomNumber != null) house.setRoomNumber(roomNumber);
        if (remark != null) house.setRemark(remark);
        if (ownerId != null){
            house.setOwnerId(ownerId);
            if (checkInDate == null) return AjaxResult.fail("需要与户主信息一起同步填写入住日期");
            DateUtil.stringToDate(checkInDate);
            house.setCheckInDate(checkInDate);
        }
        boolean updated = houseService.updateHouse(house);
        return updated ? AjaxResult.success(house) : AjaxResult.fail("房屋更新失败");
    }

    /**
     * 根据ID删除房屋信息
     * @param id 房屋ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "【管理员】根据ID删除房屋信息", notes = "根据房屋ID删除房屋信息")
    @ApiImplicitParam(name = "id", value = "房屋ID", required = true, dataType = "Long", paramType = "path")
    public AjaxResult deleteHouse(@RequestHeader("Authorization") String token, @PathVariable Long id) {
        boolean deleted = houseService.removeById(id);
        if (deleted) {
            return AjaxResult.success("房屋删除成功");
        } else {
            return AjaxResult.fail("房屋删除失败");
        }
    }
}
